package com.klun.concDesign.chapterFive.Curr_5_7;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 并行搜索
 *
 */
public class SearchTask implements Callable<Integer> {

    int begin,end,searchValue;
    static int[] arr;
    static ExecutorService pool = Executors.newCachedThreadPool();
    static final int Thread_Num = 2;
      static AtomicInteger result = new AtomicInteger(-1);

    public SearchTask(int begin, int end, int searchValue) {
        this.begin = begin;
        this.end = end;
        this.searchValue = searchValue;
    }

    @Override
    public Integer call() throws Exception {
        int search = search(searchValue, begin, end);
        return search;
    }

    public static int search(int searchValue,int beginPos,int engPos){
        int i = 0;
        for (int j = beginPos; j < engPos; j++) {
            if(result.get() > 0){
                // 如果 > 0 证明已经检索到了
                return result.get();
            }
            // 进入下面的 if 证明匹配到了要找的数
            if(arr[i] == searchValue){
                // 如果设置失败，表示其他线程已经先找到了
                if(!result.compareAndSet(-1,j)){
                    return result.get();
                }
                return j;
            }
        }
        return -1;
    }

    public static int pSearch(int searchValue) throws ExecutionException, InterruptedException {
        int subArrSize = arr.length/Thread_Num+1;
        List<Future<Integer>> re = new ArrayList<>();
        for (int i = 0; i < arr.length; i+=subArrSize) {
            int end = i+subArrSize;
            if(end > arr.length) end = arr.length;
            re.add(pool.submit(new SearchTask(searchValue,i,end)));
        }
        for (Future<Integer> fu : re){
            if(fu.get()>0){
                return fu.get();
            }
        }
        return -1;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        pSearch(10);
    }
}
